// 云函数入口文件
const cloud = require('wx-server-sdk')
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let r
  clearRecords()
  updateTreasurePrice()
  updateUserInfo()

  //清理record
  async function clearRecords() {
    let day = new Date(Date.now() - (3 * 24 * 60 * 60 * 1000 + 8 * 60 * 60 * 1000))
    console.log(day)
    let res = await db.collection('Record').where({
      createTime: _.lt(day)
    }).remove()
    console.log("clearRecords = 'ok'", res)
  }
  //更新宝石每日成交价
  async function updateTreasurePrice() {
    let res2 = await db.collection('Setting').doc('5a93cec95edf0fc400679b4f23f37a84')
      .get()
    let treasures = res2.data.treasures
    for (let i = 0; i < treasures.length; i++) {
      let rate = ((Math.random() * 20) - 10) / 100
      let price = Math.floor(treasures[i].price * (1 + rate))
      treasures[i].price = price
      treasures[i].rate = rate
    }

    await db.collection('Setting').doc('5a93cec95edf0fc400679b4f23f37a84')
      .update({
        data: {
          treasures: treasures
        }
      })
    console.log("updateTreasurePrice = 'ok'")
  }
  //更新用户每日
  async function updateUserInfo() {
    let day = new Date(Date.now() + (8 * 60 * 60 * 1000))
    let today = day.getFullYear().toString() + (day.getMonth() + 1).toString() + day.getDate().toString();

    let userCount = await db.collection('User').count()
    let total = userCount.total
    let list = []
    for (let j = 0; j < total; j += 100) {
      list = list.concat(await getList(j));
    }
    for (i = 0; i < list.length; i++) {
      let houseLife, roomSum
      if (list[i].house.roomSum == 0 && list[i].house.life <= 10) {
        houseLife = 0
        roomSum = 0
      } else if (list[i].house.roomSum > 0 && list[i].house.life <= 10) {
        houseLife = 100
        roomSum = list[i].house.roomSum - 1
      } else {
        houseLife = list[i].house.life - 10
        roomSum = list[i].house.roomSum
      }

      let life = list[i].pet.life < 4 ? list[i].pet.life : 4
      let charm = list[i].pet.charm < 4 ? list[i].pet.charm : 4

      //更新用户数据
      let res = await db.collection('User').doc(list[i]._id)
        .update({
          data: {
            loginDay: today,
            dialTimes: 0,
            openBoxTimes: 0,
            'house.life': houseLife,
            'house.roomSum': roomSum,
            'pet.life': _.inc(-life),
            'pet.charm': _.inc(-charm)
          }
        })
    }
    console.log("updateUserInfo = 'ok'")
  }

  async function getList(skip) {
    let res = await db.collection('User')
      .skip(skip).get()
    return res.data;
  }

}